package com.vgooo.client.mobile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.CustomField;
import com.vgooo.bean.MobileAlbum;
import com.vgooo.bean.Price;
import com.vgooo.bean.ProdDetail;
import com.vgooo.bean.ProdInfo;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.ui.HorizontalListView;
import com.vgooo.client.ui.VGScrollView;
import com.vgooo.client.ui.VGWebView;
import com.vgooo.client.ui.ViewPagerAdapter;
import com.vgooo.client.vchannel.PingActivity;
import com.vgooo.client.vchannel.PingDetail;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.Loading.Progress;
import com.vgooo.util.UmengUtils;
import com.vgooo.util.Utils;

public class MobileDetailActivity_v2 extends VGActivity {

	String className = getClass().getSimpleName();// 类名，用于打印调试信息

	private ProdInfo prodInfo;// 热门推荐手机信息
	private ProdDetail prodDetail;// 手机详情
	private ImageView search;// 顶部搜索
	private ImageView back;// 顶部返回按钮
	// private TextView prodName;// 产品名称

	private ImageView prodImage;// 产品图片

	private TextView[] customText;// 操作系统 、摄像头、 屏幕大小 、屏幕分辨率文本
	private ImageView[] customImage;// 操作系统 、摄像头、 屏幕大小 、屏幕分辨率图片

	private TextView prodContentStandard;// 标准配置
	
	private TextView title; //手机名称

	private HorizontalListView prodAlbumList;// 产品图赏列表

	private List<MobileAlbum> albums;// 产品图赏信息

	private MobileAlbumAdapter mobileAlbumAdapter;// 产品图赏适配器

	private LinearLayout moreDetail;// 更多参数详情视图

	private boolean showMore = false;// 标记显示更多详情

	// private ImageView smImage;// 显示更多展开图标

	private TextView contentBasicParam; // 更多参数
	private TextView pingCount ;

	private com.vgooo.client.ui.VGWebView webView;
//	private WebView webView;

	// 请求参数
	private String prod_html;
	private String brand_html;

	private OnClickListener rBListener;// 单击事件监听器

	public LinearLayout pricesRoot;// 手机售价单选按钮的父容器
	public TextView[] radioButtons;// 版本单选按钮
	public TextView[] radioTypes;// 版本型号
	public TextView[] radioPrices;// 价格显示文本
	public int rbIndex;// 选中版本的索引
	public int rbLen;// 版本单选按钮的个数

	// private View ping;

	private com.vgooo.client.ui.VGScrollView scrollView;

	private PingDetail pingDetail;

	private boolean isFirstLoading = true;

//	private boolean loadSuccesss = false;

	private String link = "";

//	private String prodName = "网络异常";

	private int standarWidth = 0;
	
//	private com.vgooo.client.ui.VGViewPager  viewPager ; 
	private ViewPager  viewPager ; 
	
	private View titleView ;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		detailVeiw = inflater.inflate(R.layout.mobile_detail_v2, null);

		setContentView(detailVeiw);
		detailVeiw.setVisibility(View.INVISIBLE);
		initView();

		needNewProgress = true;
		standarWidth = Utils.getSceenWidth(context);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// setContentView(detailVeiw);
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		String link = Main.moblieDetailIntent.getStringExtra("link");
		// String link = getIntent().getStringExtra("link");
		if(null==link||"".equals(link)||link.trim().length()<1){
			ViewLayout.setViewBack();
			return ;
		}
		DebugTools.log(className, link.toString());
		if (this.link.equals(link)) {
			isFirstLoading = false;
			detailVeiw.setVisibility(View.VISIBLE);
			// 显示产品名称
			return;
		} else {

			detailVeiw = inflater.inflate(R.layout.mobile_detail_v2, null);

			setContentView(detailVeiw);
			detailVeiw.setVisibility(View.INVISIBLE);

			initView();
			addListener();

//			pingDetail.isShowPing = false;
			this.link = link;
			init();
		}
		
		
		
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
		// pingCurrentPage = 0;
		Utils.hideSoftInput(detailVeiw);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		
		
		viewPager = (ViewPager) findViewById(R.id.mobile_detail_view_pager);
		
		scrollView = (VGScrollView) inflater.inflate(R.layout.mobile_detial_content, null);
		prodImage = (ImageView) scrollView.findViewById(R.id.mobile_detail_image);

		pricesRoot = (LinearLayout) scrollView.findViewById(R.id.mobile_detail_prices_root);
		
		title = (TextView) scrollView.findViewById(R.id.mobile_detail_title) ;
		
		customText = new TextView[5];
		customText[0] = (TextView) scrollView.findViewById(R.id.mobile_detail_system);// 操作系统
		customText[1] = (TextView) scrollView.findViewById(R.id.mobile_detail_camera);// 摄像头
		customText[2] = (TextView) scrollView.findViewById(R.id.mobile_detail_screensize);// 屏幕大小
		customText[3] = (TextView) scrollView.findViewById(R.id.mobile_detail_resolution);// 屏幕分辨率
		customText[4] = (TextView) scrollView.findViewById(R.id.mobile_detail_cell_capacity);// 电池容量

		customImage = new ImageView[5];
		customImage[0] = (ImageView) scrollView.findViewById(R.id.mobile_detail_system_image);// 操作系统图片
		customImage[1] = (ImageView) scrollView.findViewById(R.id.mobile_detail_camera_image);// 摄像头图片
		customImage[2] = (ImageView) scrollView.findViewById(R.id.mobile_detail_screensize_image);// 屏幕大小图片
		customImage[3] = (ImageView) scrollView.findViewById(R.id.mobile_detail_resolution_image);// 屏幕分辨率图片
		customImage[4] = (ImageView) scrollView.findViewById(R.id.mobile_detail_cell_capacity_image);// 电池容量图片

		prodContentStandard = (TextView) scrollView.findViewById(R.id.mobile_detail_content_standard);// 标配

		prodAlbumList = (HorizontalListView) scrollView.findViewById(R.id.mobilee_detial_prod_album_list);// 手机图片列表

		contentBasicParam = (TextView) scrollView.findViewById(R.id.mobile_detail_content_basic_param);// 更多参数

		// 更多详情的父容器
		moreDetail = (LinearLayout) scrollView.findViewById(R.id.mobile_detial_more_detail);
		// smImage = (ImageView) findViewById(R.id.mobile_detail_more_image);

		// 更多详情
		webView = (VGWebView) scrollView.findViewById(R.id.mobile_detail_webview);
		// 显示产品更多介绍
		webView.setVisibility(WebView.VISIBLE);		
		webView.setInitialScale(150);
		
		webView.addJavascriptInterface(this, "android");
		WebSettings setting = webView.getSettings();
		setting.setUseWideViewPort(false);
		setting.setSupportZoom(false);
		setting.setDefaultTextEncodingName("UTF-8");// 设置编码
		setting.setPluginsEnabled(true);// 是否支持插件
		setting.setJavaScriptEnabled(true);// 设置是否支持javaScript
		// 评论
		pingDetail = new PingDetail(cparent, PingActivity.TYPE_PROD);
		pingDetail.initView(detailVeiw.findViewById(R.id.mobile_detail_ping) );
				
		pingCount = (TextView) findViewById(R.id.ping_bottom_layout_button);

	}
	@Override
	public void setupView() {
		// TODO Auto-generated method stub
		// setContentView(detailVeiw);
		List<View> views = new ArrayList<View>();
		views.add(scrollView);
//		views.add(pingDetail.getmPullDownView());
		viewPager.setAdapter(new ViewPagerAdapter(viewPager,views,pingCount,prodDetail.prod_ping,pingDetail,null));

		viewPager.setCurrentItem(1);

		// 加载产品图片
		BitmapUtils.loaderImage(prodDetail.prod_image, prodImage, this);
		// 显示产品名称
//		Main.title.setText(prodName);
		title.setText(prodDetail.brand_name+" ("+prodDetail.prod_html+")") ;
		// Main.title2.setText(prodName);

		// 加载产品价格信息
		radioButtons = new TextView[rbLen];
		radioTypes = new TextView[rbLen];
		radioPrices = new TextView[rbLen];
		pricesRoot.removeAllViews();
		for (int i = 0; i < rbLen; i++) {
			View price = inflater.inflate(R.layout.prce_item, null);
			price.setOnClickListener(new MyRBClickListener(this));
			price.setTag(i);
			radioButtons[i] = (TextView) price
					.findViewById(R.id.price_item_type_rgbt);
			radioTypes[i] = (TextView) price.findViewById(R.id.price_item_type);
			radioPrices[i] = (TextView) price
					.findViewById(R.id.price_item_price);

			radioTypes[i].setText(prodDetail.prices[i].price_prefix + "：");
			;
			radioPrices[i].setText(prodDetail.prices[i].price_sell);

			pricesRoot.addView(price);

		}

		

		// 加载产品参数，系统、分辨率、屏幕大小。。。
		int i = 0;
		for (CustomField customField : prodDetail.customFields) {
			customText[i].setText(customField.value);
			// fb.display(customImage[i], customField.image);
			// BitmapUtils.loaderImage(customField.image, customImage[i],this);

			i++;
		}

		// 显示产品标配信息
		prodContentStandard.setText(prodDetail.prices[0].content_standard);

//		moreDetail.setVisibility(View.GONE);
		showMore = false;
		// smImage.setBackgroundResource(R.drawable.ex_lv_ex_no);

		// 显示产品图赏列表
		mobileAlbumAdapter = new MobileAlbumAdapter(albums, this);
		prodAlbumList.setAdapter(mobileAlbumAdapter);
		

		// 显示产品详情
		// 显示带Html标签的文本
		// CharSequence html = Html.fromHtml(prodDetail.content_basic_param);
		// contentBasicParam.setText(html);
		webView.loadUrl("");
		webView.loadDataWithBaseURL(null, prodDetail.contents, "text/html",
				"UTF-8", null);
		isFirst = false;
		moreDetail.setVisibility(View.VISIBLE);
		// smImage.setBackgroundResource(R.drawable.ex_lv_ex);
		showMore = !showMore;
		titleView =  inflater.inflate(R.layout.layout_mobile_title, null);
		((TextView)titleView.findViewById(R.id.mobile_detail_title)).setText(title.getText());
		pingDetail.setupView(prodDetail.prod_ping, prodDetail.prod_id,titleView);

		detailVeiw.setVisibility(View.VISIBLE);
		
		

	}

	@Override
	public void addListener() {
		// TODO Auto-generated method stub

		prodAlbumList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				MobileAlbum album = albums.get(position);
				DebugTools.log(className, album.toString());
				Main.moblieAlbumIntent.putExtra("id", album.image_prod_id);
				Main.moblieAlbumIntent.putExtra("image_id",
						album.image_id);
				ViewLayout.setViewPre(true, "产品图赏",
						ViewLayout.TAB_TAG_MOBILE_ALBUM,cparent);
			}
		});
		
		
		webView.setWebChromeClient(new WebChromeClient(){

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if(newProgress==100){
					
				}
				super.onProgressChanged(view, newProgress);
			}
			
		});
		
		webView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
//				webView.clearFocus();
//				scrollView.scrollTo(scrollView.getScrollX(), temp_Srolly);
				if(event.getAction()== MotionEvent.ACTION_DOWN){
					int temp_Srolly = webView.getScrollY() ;
					webView.scrollTo(webView.getScrollX(), temp_Srolly +1) ;
					webView.scrollTo(webView.getScrollX(), temp_Srolly);
				}
				if(event.getAction()== MotionEvent.ACTION_UP){
					scrollView.requestFocus();
					int temp_Srolly = scrollView.getScrollY() ;
					scrollView.scrollTo(scrollView.getScrollX(), temp_Srolly +10) ;
				}
				return false;
			}
		});

		
	}

	@Override
	public void flashView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getData() {
		try {
			// TODO Auto-generated method stub
			String urlPath = HttpUtils.BASE_URI + link;
//			prodName = "网络异常";
			String jsonString = HttpUtils.getJsonString(urlPath.toString());
			DebugTools.log(className, "jsonString = " + jsonString);
			Map<String, Object> prods = GSonTools.getObjectMaps(jsonString);
			DebugTools.log(className, "prods = " + prods);
			Map<String, Object> brand = (Map<String, Object>) prods
					.get("brand");
			prodDetail = new ProdDetail();
			prodDetail.brand_name = (String) brand.get("brand_name");
			prodDetail.brand_html = (String) brand.get("brand_html");

			Map<String, Object> prod = (Map<String, Object>) prods.get("prod");
			prodDetail.prod_image = (String) prod.get("prod_image");
			prodDetail.prod_id = (String) prod.get("prod_id");
			prodDetail.prod_html = (String) prod.get("prod_html");
			prodDetail.brand_name += " " + (String) prod.get("prod_name");
//			prodName = prodDetail.brand_name;

		
			
			new WebAsyncTash().execute("");
			List<Map<String, Object>> prices = (List<Map<String, Object>>) prods
					.get("prices");
			int len = prices.size();
			prodDetail.prices = new Price[len];
			rbLen = len;
			for (int j = 0; j < len; j++) {
				Map<String, Object> price = prices.get(j);
				prodDetail.prices[j] = new Price();
				prodDetail.prices[j].price_sell = (String) price
						.get("price_sell");
				prodDetail.prices[j].price_prefix_image = (String) price
						.get("price_prefix_image");
				prodDetail.prices[j].price_prefix = (String) price
						.get("price_prefix");
				Map<String, String> type = (Map<String, String>) price
						.get("type");
				prodDetail.prices[j].content_standard = (String) type
						.get("content_standard");
				DebugTools.log(className, "prodDetail.prices[" + j
						+ "].content_standard = "
						+ prodDetail.prices[j].content_standard);
				DebugTools.log(className, "prodDetail.prices[" + j
						+ "].price_sell = " + prodDetail.prices[j].price_sell);
			}

			prodDetail.contents = (String) prods.get("contents");
			prodDetail.content_basic_param = (String) prods
					.get("content_basic_param");
			prodDetail.contents = prodDetail.content_basic_param ;

			List<Map<String, Object>> customFields = (List<Map<String, Object>>) prods
					.get("customFields");
			len = customFields.size();
			prodDetail.customFields = new CustomField[len];
			for (int j = 0; j < len; j++) {
				Map<String, Object> fields = (Map<String, Object>) customFields
						.get(j);
				DebugTools.log(className, "fields = " + fields);
				String images_src = (String) fields.get("images_src");
				String values = (String) fields.get("values");
				prodDetail.customFields[j] = new CustomField(values, images_src);
				DebugTools.log(className, "values = " + values);
				DebugTools.log(className, "prodDetail.customFields[j].value = "
						+ prodDetail.customFields[j].value);

				prodDetail.prod_ping = (String) prods.get("prod_ping");

			}

			urlPath = HttpUtils.BASE_URI + "prodcontentmakethumb?pid="
					+ prodDetail.prod_id + "&sw=" + Utils.dip2px(cparent, 320);

			// 获取产品图赏信息
			urlPath = HttpUtils.BASE_URI + "prodpics?id=" + prodDetail.prod_id;
			jsonString = HttpUtils.getJsonString(urlPath);
			// DebugTools.log(className, "mobileAlbum : " + jsonString);
			List<Map<String, Object>> list = GSonTools
					.getMulObjectList(jsonString);
			albums = new ArrayList<MobileAlbum>();
			// Set<String> keySet = map.keySet() ;
			// DebugTools.log(className, "keySet : " + keySet);

			for (Map<String, Object> m : list) {
				MobileAlbum album = new MobileAlbum();
				album.image_id = (String) m.get("image_id");
				album.image_prod_id = (String) m.get("image_prod_id");
				album.image_nickname = (String) m.get("image_nickname");
				album.image_src = (String) m.get("image_src");
				Map<String, Object> photos = (Map<String, Object>) m
						.get("photos");
				album.sort_id = (String) photos.get("sort_id");
				album.sort_name = (String) photos.get("sort_name");
				album.sort_prod_id = (String) photos.get("sort_prod_id");
				albums.add(album);
			}

			isFirst = true;

			isFirstLoading = true;

//			pingActivity.isFirstLoadingPing = true;
			
			
			


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0&&null!=pingDetail) {
			if(pingDetail.isEdit){
				pingDetail.chanageEdit(false);
				return true ;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	class MyRBClickListener implements OnClickListener {

		private Context context;

		public MyRBClickListener(Context context) {
			super();
			this.context = context;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int tag = (Integer) v.getTag();
			// 更换产品图片
			// BitmapUtils.loaderImage(prodDetail.prices[tag].price_prefix_image,
			// prodImage,this);
			BitmapUtils.loaderImage(prodDetail.prices[tag].price_prefix_image,
					prodImage, context);
			// 更换产品标配
			prodContentStandard
					.setText(prodDetail.prices[tag].content_standard);
			DebugTools.log(className, tag + "");
			for (int j = 0; j < rbLen; j++) {
				if (j == tag) {
					radioButtons[j]
							.setBackgroundResource(R.drawable.rg_button_bg_selected);
				} else {
					radioButtons[j]
							.setBackgroundResource(R.drawable.rg_button_bg_inselected);
				}
			}
		}

	}

	@Override
	public void doClick(View v) {
		// TODO Auto-generated method stub

		// String parent_id = null ;
		switch (v.getId()) {

		default:
			if (pingDetail != null) {
				pingDetail.doClick(v);
			} else {
				DebugTools.log(className,
						"doClick() 未定义控件单击后的事件......" + v.getId());
			}
			break;
		}
	}

	class WebHandler extends Handler {
		private Progress progressDialog;
		private Context context;

		public WebHandler(Progress progressDialog, Context context) {
			super();
			this.progressDialog = progressDialog;
			this.context = context;
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case VGActivity.LOADER_SUCCESS:
				webView.loadUrl("");
				webView.loadDataWithBaseURL(null, prodDetail.contents,
						"text/html", "UTF-8", null);
				// progressDialog.setCancelable(true);
				DebugTools.log(className, prodDetail.contents);
				progressDialog.cancel();
				break;
			case VGActivity.LOADER_FAIL:
				// progressDialog.setCancelable(true);
				progressDialog.cancel();
				Toast.makeText(context, "网络异常", Toast.LENGTH_LONG).show();
				break;

			default:
				break;
			}
		}
	}

	class WebDataAsyncLoader extends AsyncTask<String, String, String> {
		private Handler handler;
		private Context context;

		public WebDataAsyncLoader(Handler handler) {
			this.handler = handler;
		}

		public WebDataAsyncLoader(Handler handler, Context context) {
			super();
			this.handler = handler;
			this.context = context;
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				String urlPath = HttpUtils.BASE_URI + "prodgetcontentdesc?pid="
						+ prodDetail.prod_id + "&sw=" + standarWidth + "&dp="
						+ Utils.getSceenWidth(context);
				String jsonString = HttpUtils.getJsonString(urlPath);
				DebugTools.log(className, jsonString);
				Map<String, Object> map = GSonTools.getObjectMaps(jsonString);
				prodDetail.contents = (String) map.get("contents");
				handler.sendEmptyMessage(VGActivity.LOADER_SUCCESS);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				handler.sendEmptyMessage(VGActivity.LOADER_FAIL);
				prodDetail.contents = e.toString();
				e.printStackTrace();
				UmengUtils.onError(context, e.toString());
			}
			return null;
		}

	}

	// AsyncTask as = new AsyncTask<Params, Progress, Result>
	
	
	private  class WebAsyncTash extends AsyncTask<String, String, String>{

		private boolean loadDeialSuccess = false;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			new Thread(){
				public void run() {
					String url = null ;
					try {
						url = HttpUtils.BASE_URI + "prodcontentmakethumb?pid="
								+ prodDetail.prod_id + "&sw=" + standarWidth;
						HttpUtils.getJsonString(url);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}finally{
						url = null ;
					}
				};
			}.start();
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
//			String url = HttpUtils.BASE_URI + "prodcontentmakethumb?pid="
//					+ prodDetail.prod_id + "&sw=" + standarWidth;
			
			try {
			String	urlPath = HttpUtils.BASE_URI + "prodgetcontentdesc?pid="
						+ prodDetail.prod_id + "&sw=" + standarWidth + "&dp="
						+ Utils.getSceenWidth(context);Log.i("aaaaaaa", urlPath);
				String jsonString2 = HttpUtils.getJsonString(urlPath);
				urlPath = null ;
				prodDetail.contents = jsonString2;
//				HttpUtils.getJsonString(url);
				loadDeialSuccess = true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				loadDeialSuccess = false;
				UmengUtils.onError(context, e.toString());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (loadDeialSuccess) {
				webView.loadDataWithBaseURL(null, "",
						"text/html", "UTF-8", null);
				webView.loadDataWithBaseURL(null, prodDetail.contents,
						"text/html", "UTF-8", null);
			}
			super.onPostExecute(result);
		}
	}
	
	
	private static void log(String info){
		Log.i("MobileDetailActivity", info);
	}
}
